import type { Dispatch } from "react";
import { message } from "@/utils/staticAntd";
import { ServerResult } from "@/api/request/types";

type IParams<T = unknown> = {
	params: T;
	apiFn: (data?: any) => Promise<ServerResult<object>>;
	dispatch: Dispatch<unknown>;
	setDataFn: (params?: any, payload?: any) => void;
	isOrigin?: boolean;
};

export async function handleData(obj: IParams): Promise<any> {
	const { apiFn, dispatch, setDataFn, params } = obj;
	try {
		const res = await apiFn(params);
		if (res?.code === 200) {
			return await dispatch(setDataFn(res.data));
		}
		if (res?.code === 40010 || res?.code === 40011) {
			message.warning(res?.msg || "网络开小差");
			// 需要验证码
			return await dispatch(setDataFn(res));
		}
		message.warning(res?.msg || "网络开小差");
	} catch (error) {
		message.error("服务异常");
		console.log(error);
	}

	return {
		payload: {}
	};
}
